<!DOCTYPE html>
<html>
<head>
    <title>简单上传测试</title>
    <meta charset="utf-8">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .result { margin: 10px 0; padding: 10px; border: 1px solid #ccc; }
        .success { background-color: #d4edda; border-color: #c3e6cb; }
        .error { background-color: #f8d7da; border-color: #f5c6cb; }
        button { padding: 8px 16px; margin: 5px; }
        input { margin: 5px; padding: 5px; }
    </style>
</head>
<body>
    <h1>音频上传功能测试</h1>
    
    <div>
        <h3>1. 服务器连接测试</h3>
        <button onclick="testServer()">测试服务器</button>
        <div id="serverResult"></div>
    </div>
    
    <div>
        <h3>2. 音频上传测试</h3>
        <input type="file" id="audioFile" accept="audio/*">
        <input type="text" id="songTitle" placeholder="歌曲名" value="测试歌曲">
        <input type="text" id="artistName" placeholder="艺术家" value="测试艺术家">
        <button onclick="uploadTest()">上传测试</button>
        <div id="uploadResult"></div>
    </div>

    <script>
        const SERVER_URL = 'http://localhost:3000';
        
        async function testServer() {
            const resultDiv = document.getElementById('serverResult');
            resultDiv.innerHTML = '<div>正在测试服务器连接...</div>';
            
            try {
                // 测试基本连接
                const response = await fetch(SERVER_URL + '/', {
                    method: 'GET',
                    mode: 'cors'  // 明确设置CORS模式
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                resultDiv.innerHTML = `
                    <div class="result success">
                        ✅ 服务器连接成功<br>
                        消息: ${data.message}<br>
                        状态: ${data.status || 'ok'}
                    </div>
                `;
                
                // 测试上传端点
                const uploadResponse = await fetch(SERVER_URL + '/api/upload/audio', {
                    method: 'OPTIONS',
                    mode: 'cors'
                });
                
                resultDiv.innerHTML += `
                    <div class="result success">
                        ✅ 上传端点可访问 (状态: ${uploadResponse.status})
                    </div>
                `;
                
            } catch (error) {
                console.error('服务器测试失败:', error);
                resultDiv.innerHTML = `
                    <div class="result error">
                        ❌ 服务器连接失败<br>
                        错误: ${error.message}<br>
                        建议: 请确保服务器在 ${SERVER_URL} 运行
                    </div>
                `;
            }
        }
        
        async function uploadTest() {
            const fileInput = document.getElementById('audioFile');
            const titleInput = document.getElementById('songTitle');
            const artistInput = document.getElementById('artistName');
            const resultDiv = document.getElementById('uploadResult');
            
            if (!fileInput.files[0]) {
                resultDiv.innerHTML = '<div class="result error">❌ 请先选择音频文件</div>';
                return;
            }
            
            const file = fileInput.files[0];
            console.log('选择的文件:', {
                name: file.name,
                size: file.size,
                type: file.type
            });
            
            // 检查文件类型
            if (!file.type.startsWith('audio/')) {
                resultDiv.innerHTML = '<div class="result error">❌ 请选择音频文件</div>';
                return;
            }
            
            const formData = new FormData();
            formData.append('audio', file);
            formData.append('title', titleInput.value);
            formData.append('artist', artistInput.value);
            
            resultDiv.innerHTML = '<div>🔄 正在上传...</div>';
            
            try {
                const response = await fetch(SERVER_URL + '/api/upload/audio', {
                    method: 'POST',
                    body: formData,
                    mode: 'cors'
                });
                
                console.log('上传响应:', response);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }
                
                const result = await response.json();
                console.log('上传结果:', result);
                
                if (result.code === 0) {
                    resultDiv.innerHTML = `
                        <div class="result success">
                            ✅ 上传成功！<br>
                            文件名: ${result.data.filename}<br>
                            原始名: ${result.data.originalName}<br>
                            大小: ${(result.data.size / 1024 / 1024).toFixed(2)} MB<br>
                            URL: ${result.data.audioUrl}<br>
                            <audio controls style="width: 100%; margin-top: 10px;">
                                <source src="${SERVER_URL}${result.data.audioUrl}" type="audio/mpeg">
                                您的浏览器不支持音频播放
                            </audio>
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = `
                        <div class="result error">
                            ❌ 上传失败<br>
                            错误: ${result.message}
                        </div>
                    `;
                }
                
            } catch (error) {
                console.error('上传错误:', error);
                resultDiv.innerHTML = `
                    <div class="result error">
                        ❌ 上传失败<br>
                        错误: ${error.message}
                    </div>
                `;
            }
        }
        
        // 页面加载时自动测试服务器
        window.onload = () => {
            console.log('页面加载，开始测试服务器...');
            testServer();
        };
    </script>
</body>
</html>